package com.klitors.creator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.Map;

import com.klitors.creator.utils.CreateUtils;
import com.klitors.creator.utils.FileUtils;


/**
 * @author 66
 * @date 2016年10月11日
 */
public class TextOut {
	/**
	 * @param txt
	 *            写好的源文件，相对于cn/itheima/create的地址
	 * @param file
	 *            要输出到的文件，如果文件已经存在则跳过
	 * @param props
	 *            要替换的变量，将对应的键替换为值
	 * @return 
	 */
	public static File file(String from, String to, Map<String, String> props) {
		File toFile = new File(to);
		if(FileUtils.fileExists(toFile)){
			return  toFile;
		}
		//如果输入文件有创建类型，则加入创建类型
		String create_pattern = props.get("create_pattern");
		if(create_pattern!=null&&!create_pattern.equals("")){
			from = FileUtils.mkPath(create_pattern,from);
		}
		InputStream is = TextOut.class.getResourceAsStream(from);
		if (is == null) {
			System.out.println("输入文件地址出错：" + from);
		}
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(is));
				PrintWriter pw = new PrintWriter(new FileWriter(toFile));) {

			// 按行操作
			String line;
			while ((line = reader.readLine()) != null) {
				// 修改参数
				line = mkProp(line, props);
				// 输出到java文件中
				pw.println(line);
			}
			System.out.println("生成：" + toFile.getName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return toFile;
	}

	public static String mkProp(String line, Map<String, String> props) {
		// 不包含 ${} 则跳过
		if (!line.matches(".*[$][{].*[}].*"))
			return line;
		// 获取${}中的变量名
		String prop = line.substring(line.indexOf("${") + 2, line.indexOf("}"));
		if (prop.contains(":")) {
			// 有特殊变量，（循环）
			String sp = switchProp(prop);
			return sp;
		}
		if (props.containsKey(prop)) {
			// 有这个变量则替换其值
			line = line.replace("${" + prop + "}", props.get(prop));
		} else {
			// 没有则去掉${}
			line = line.replace("${" + prop + "}", prop);
		}
		// 返回修改后的行数据
		return mkProp(line, props);
	}

	private static String switchProp(String prop) {
		String sp = prop.substring(0, prop.indexOf(":"));
		return sp;
	}

	public static void hbm(Properties props, File file) {
		String bean_name = props.get("bean_name");
		String lower_name = props.get("lower_name");
		String bean_package = props.get("bean_package");
		String id_name = props.get("id_name");
		Field[] df = props.getClazz().getDeclaredFields();
		// 如果文件存在则跳过
		if (file.exists()) {
			return;
		}
		PrintWriter pw = null;
		try {
			file.createNewFile();
			pw = new PrintWriter(new FileWriter(file));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 进行输出-------------------------------------------
		pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		pw.println("<!DOCTYPE hibernate-mapping PUBLIC");
		pw.println("    \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"");
		pw.println("    \"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\">");
		pw.println("<hibernate-mapping package=\"" + bean_package + "\">");
		pw.println("	<class name=\"" + bean_name + "\" table=\"" + lower_name + "\">");
		pw.println("		<id name=\"" + id_name + "\">");
		pw.println("			<generator class=\"native\"></generator>");
		pw.println("		</id>");
		for (int i = 1; i < df.length; i++) {
			String t = CreateUtils.classifyType(df[i].getType());
			if (t.equals("common") || t.equals("base")) {
				// 普通属性，使用property
				pw.println("		<property name=\"" + df[i].getName() + "\"></property>");
			} else if (t.equals("set")) {
				// 集合属性，使用set
				/*
				 * String gt = df[i].getGenericType().toString(); String
				 * fullName = CreateUtils.getGenericType(gt); String simpleName
				 * = CreateUtils.getSimpleName(fullName); pw.println(
				 * "		<set name=\""+df[i].getName()+"s\">"); pw.println(
				 * "			<key column=\""
				 * +lower_name+"_"+simpleName+"_id\"></key>"); pw.println(
				 * "			<one-to-many class=\""+fullName+"\" />");
				 * pw.println("		</set>");
				 */
			}
		}
		pw.println("	</class>");
		pw.println("</hibernate-mapping>");
		// -------------------------------------------------
		System.out.println("生成：" + file.getName());
		pw.close();
	}
}
